package com.bc.commoncore.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtil {
    public static final String yyyy_MM_dd_HH_mm_ss = "yyyy/MM/dd HH:mm:ss";
    private static final Logger logger = LoggerFactory.getLogger(DateUtil.class);

    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     *
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00
     * @return long[] 返回值为：{天, 时, 分, 秒}
     */
    public static long[] getDistanceTimes(String str1, String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        long[] times = {day, hour, min, sec};
        return times;
    }

    /**
     * @return 按指定的时间格式返回时间，如果为空则按yyyy-MM-dd HH:mm:ss格式返回
     * @para format 时间格式
     */
    public static String getToday(String format) {
        if (format == null)
            format = "yyyy-MM-dd HH:mm:ss";

        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("-480"));

        SimpleDateFormat ft = new SimpleDateFormat(format);
        return ft.format(c.getTime());
    }

    public static String formatDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmm");
        return format.format(date);
    }

    /**
     * 格式化时间
     *
     * @param date   待格式化的时间
     * @param format 时间格式
     * @return 返回格式化后的时间
     */
    public static String formartDate(Date date, String format) {
        if (format == null)
            format = "yyyy-MM-dd HH:mm:ss";
        if (date == null) {
            return "";
        }
        SimpleDateFormat ft = new SimpleDateFormat(format);
        return ft.format(date);
    }

    public static Date formatDate(String date, String formatStr) {
        Date date1 = null;
        try {
            SimpleDateFormat formatCus = new SimpleDateFormat(formatStr);
            date1 = formatCus.parse(date);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return date1;
    }

    public static Date getToday() {
        return DateUtil.formatDate(DateUtil.getToday(null), "yyyy-MM-dd HH:mm:ss");
    }

    public static Date getDate(String date) {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return df.parse(date);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 当前时间与指定时间的间隔天数
     *
     * @param enddate 时间
     * @return 返回间隔的天数
     */
    public static long getDateNum(Date enddate) {
        Calendar startDate = Calendar.getInstance();
        startDate.setTime(new Date());
        Calendar endDate = Calendar.getInstance();
        endDate.setTime(enddate);
        long subDay = (endDate.getTimeInMillis() - startDate.getTimeInMillis())
                / 1000 / 60 / 60 / 24;
        //System.out.println(subDay);

        return subDay;

    }

    /**
     * 任意两个时间段的间隔小时
     *
     * @param startDate 开始时间
     * @param endDate   截止时间
     * @return 返回间隔的小时
     */
    public static long getHourNum(Date startDate, Date endDate) {

        Calendar enddate = Calendar.getInstance();
        enddate.setTime(endDate);

        Calendar startdate = Calendar.getInstance();
        startdate.setTime(startDate);

        long subHour = (enddate.getTimeInMillis() - startdate.getTimeInMillis()) / 1000 / 60 / 60;

        return subHour;

    }

    /**
     * 取当前时间距当天时间剩多少秒
     *
     * @return
     */
    public static long getCurrentSecondNum() {
        try {
            final Calendar cal = Calendar.getInstance();
            cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + 1);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return -1;
        }
    }

    /**
     * 任意两个时间段的间隔天数
     *
     * @param startDate 开始时间
     * @param endDate   截止时间
     * @return 返回间隔的天数
     */
    public static long getDateNum(Date startDate, Date endDate) {

        Calendar enddate = Calendar.getInstance();
        enddate.setTime(endDate);

        Calendar startdate = Calendar.getInstance();
        startdate.setTime(startDate);

        long subDay = (enddate.getTimeInMillis() - startdate.getTimeInMillis())
                / 1000 / 60 / 60 / 24;

        return subDay;

    }

    /**
     * 任意两个时间段的间隔天数
     *
     * @param start 开始时间
     * @param end   截止时间
     * @return 返回间隔天数
     * @throws ParseException
     */
    public static long getDateNum(String start, String end) {

        SimpleDateFormat simFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date startDate = null;
        Date endDate = null;
        try {
            startDate = simFormat.parse(start);
            endDate = simFormat.parse(end);
            return getDateNum(startDate, endDate);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return -1;
    }

    public static long getDateNum(String start, String end, String format) {
        if (format == null) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat simFormat = new SimpleDateFormat(format);

        Date startDate = null;
        Date endDate = null;
        Calendar startCal = Calendar.getInstance();
        Calendar endCal = Calendar.getInstance();
        try {
            startDate = simFormat.parse(start);
            startCal.setTime(startDate);

            endDate = simFormat.parse(end);
            endCal.setTime(endDate);
            return startCal.getTimeInMillis() - endCal.getTimeInMillis();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return 0L;
        }
    }

    /**
     * 两个时间进行比较（按天比较）
     *
     * @param beginDate 第一个时间
     * @param endDate   第二个时间
     * @return
     */
    public static boolean isBigDate(Date beginDate, Date endDate) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(beginDate);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(endDate);
        long value = (c2.getTimeInMillis() - c1.getTimeInMillis()) / 1000 / 60
                / 60 / 24;
        if (value > 0)
            return true;
        return false;
    }

    /**
     * 两个时间进行比较（按秒比较）
     *
     * @param beginDate 第一个时间
     * @param endDate   第二个时间
     * @return
     */
    public static boolean isBigSecond(Date beginDate, Date endDate) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(beginDate);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(endDate);
        long value = (c2.getTimeInMillis() - c1.getTimeInMillis()) / 1000;
        if (value > 0)
            return true;
        return false;
    }

    /**
     * 检验时间格式是否合法
     *
     * @param input 待检验的时间
     * @return
     */
    public static boolean isDateFormat(String input) {
        boolean result = false;
        String format1 = "^(\\d{1,4})(-|\\/)(\\d{1,2})\\2(\\d{1,2})$";
        String format2 = "^(\\d{1,4})(-|\\/)(\\d{1,2})\\2(\\d{1,2}) (\\d{1,2}):(\\d{1,2}):(\\d{1,2})$";
        Pattern p = Pattern.compile(format2);
        Matcher m = p.matcher(input);
        if (m.find()) {
            result = true;
            return true;
        }
        p = Pattern.compile(format1);
        m = p.matcher(input);
        if (m.find())
            result = true;
        return result;
    }

    public static Date formatDate(String date) {
        Date date1 = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            date1 = format.parse(date);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return date1;
    }

    // solr获取时间的时候居然是用的uk时间，不懂
    // 2016年12月28日 14:33:44
    // 窦海超
    public static String GetUKTime(String date) {
        // String x = "Mon Mar 02 13:57:49 CST 2015";
        SimpleDateFormat sdf1 = new SimpleDateFormat(
                "EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
        try {
            Date d = sdf1.parse(date);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(d);
            // System.out.println(sDate);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return "";
    }

    // 累加天数
    public static String AddDay(String str, int day) {
        // Date d= formatDate(date);
        // String str = "2013-07-18";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date myDate = formatter.parse(str);
            Calendar c = Calendar.getInstance();
            c.setTime(myDate);
            c.add(Calendar.DAY_OF_YEAR, day);
            myDate = c.getTime();
            // System.out.println(formatter.format(myDate));
            return formatter.format(myDate);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return "";
    }

    public static String formatDate(long date) {
        Date date1 = new Date(date);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date1);
    }

    public static String unDoTime(SimpleDateFormat format, String repairTime,
                                  String handleTime) throws ParseException {
        long repairTimeL = format.parse(repairTime).getTime();
        long unDoTimeL = 0L;
        if ("".equals(handleTime)) {
            unDoTimeL = System.currentTimeMillis() - repairTimeL;
        } else {
            unDoTimeL = format.parse(handleTime).getTime() - repairTimeL;
        }
        long days = unDoTimeL / (24 * 3600 * 1000L);
        long hours = unDoTimeL / (3600 * 1000L) - days * 24;
        String unDoTime = days + "天" + hours + "小时";
        return unDoTime;
    }

    public static void main(String[] args) throws Exception {

        //System.out.println(60 * 60 * 24 * 30);

        Date dNow = new Date();

        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");

        Date time = DateUtil.getDate(ft.format(dNow) + " 23:59:59");
        if (time == null) {
            throw new RuntimeException("time为null");
        }
        long interval = (dNow.getTime() - time.getTime()) / 1000;

        SimpleDateFormat ftt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //System.out.println(ftt.format(dNow));
        //System.out.println(ftt.format(time));

        //System.out.println("两个时间相差"+interval+"秒");



/* 	30599秒
		getDayList("2016-01-01", "2016-2-01");
		// 当前 1448608136841
		// 45天前 1444720136841
		System.out.println(System.currentTimeMillis());
		System.out.println(System.currentTimeMillis() - 45 * 24 * 3600 * 1000L);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date d = new Date(1444720136841L + 2 * 60 * 60 * 1000L);
		String ss = sdf.format(d);
		System.out.println(ss);
		System.out.println(unDoTime(sdf, ss, ""));
		System.out.println(formatDate(new Date()));
		System.out.println(Long.valueOf(formatDate(new Date())) - 1);

		System.out.println(formartDate(new Date(), "mm"));
		System.out.println(formartDate(new Date(), "yyyy/MM/dd hh:mm:ss"));*/
    }

    /**
     * 循环某年某月的所有天数 2016年8月3日 15:06:42 窦海超
     */
    public static List<String> getDayList(String start_time, String end_time) {
        List<String> list = new ArrayList<String>();
        long dayCount = getDateNum(start_time, end_time) + 1;
        for (int i = 0; i < dayCount; i++) {
            list.add(AddDay(start_time, i));
        }
        return list;
    }

    /**
     * 得到本月的第一天
     *
     * @return
     */
    public static String getMonthFirstDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        return sdf.format(calendar.getTime());
    }

    /**
     * 得到本月的最后一天
     *
     * @return
     */
    public static String getMonthLastDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return sdf.format(calendar.getTime());
    }

    /**
     * 从英文时间转换为系统时间
     * */
    public static Date getDateByEnglishDate(String time){
        String[] timeArr=time.split(" ");
        if (timeArr.length!=3){
            return null;
        }
//        December 1st 2018
        String year=timeArr[2];

        String day=timeArr[1];
        Matcher matcher_day = Pattern.compile("(\\d+)(\\w+)")
                .matcher(day);
        day=matcher_day.find() ? matcher_day.group(1) : "";

        String month=timeArr[0];
        if (month.toLowerCase().equals("january")){
            month="01";
        }
        else if (month.toLowerCase().equals("february")){
            month="02";
        }
        else if (month.toLowerCase().equals("march")){
            month="03";
        }
        else if (month.toLowerCase().equals("april")){
            month="04";
        }
        else if (month.toLowerCase().equals("may")){
            month="05";
        }
        else if (month.toLowerCase().equals("june")){
            month="06";
        }
        else if (month.toLowerCase().equals("july")){
            month="07";
        }
        else if (month.toLowerCase().equals("august")){
            month="08";
        }
        else if (month.toLowerCase().equals("september")){
            month="09";
        }
        else if (month.toLowerCase().equals("october")){
            month="10";
        }
        else if (month.toLowerCase().equals("november")){
            month="11";
        }
        else if (month.toLowerCase().equals("december")){
            month="12";
        }
        if (day.length()<=1){
            day="0"+day;
        }
      return  getDate(year+"-"+month+"-"+day +" 00:00:00");
    }

}
